﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WMS.HelperClasses;
using WHMS.HelperClasses;
using WHMS.EntityClasses;
using SD.LLBLGen.Pro.ORMSupportClasses;
using WHMS;
using ExtendedDal;

namespace WMS
{
	public partial class AddItemsFromTransferForm : Form
	{
		TransferRequestEntity _currentTransferRequest;
		TransactionEntity _currentTransaction;
		DepositTransactionEntity _currentDepositTransaction;
		DataMngrFormBase<TransferRequestItemEntity> _tranItemsForm;
		List<ErrorProvider> _errorProviders;

		public AddItemsFromTransferForm()
		{
			InitializeComponent();
		}

		private void AddItemsForm_Load(object sender, EventArgs e)
		{			
			LoadData();

			_errorProviders = new List<ErrorProvider>();

			InitializeDataSources();
		}
		private void NewBtn_Click(object sender, EventArgs e)
		{
			//InitializeDataSources();
			//ResetTransactionItems();
			ResetForm();
		}
		private void SaveBtn_Click(object sender, EventArgs e)
		{
		    Save();
		}

	    private void Save()
	    {
	        if (!ValidateForm())
	            return;

	        if (!_currentTransaction.IsNew)
	        {
	            if ((bool)DALHelper.GetValue(DepositTransactionFields.IsPriced, DepositTransactionFields.Id, _currentDepositTransaction.Id))
	            {
	                RetrieveTransaction();
	                return;
	            }
	        }

	        var transItems = new EntityCollection<TransactionItemEntity>();
	        var transItemsToDelete = new EntityCollection<TransactionItemEntity>();

	        if (_currentDepositTransaction.IsNew)
	        {
	            //_currentDepositTransaction.SupplierId = _currentTransferRequest.SupplierId;
	            _currentDepositTransaction.SupplyOrderNumber = _currentTransferRequest.RequestNumber;

	            var transaction = new TransactionEntity()
	                                  {
	                                      ProjectId = _currentTransferRequest.ProjectId,
	                                      StoreId = GetSelectedStoreId(),
	                                      PermitNumber = PermitNumberTB.Text,
	                                      CreatedBy = UserInfo.UserId,
	                                      Date = AdditionDateDTP.Value.Date,
	                                      Type = "Deposit"
	                                  };

	            _currentDepositTransaction.Transaction = transaction;
	        }
	        else
	        {
	            DALHelper.FetchCollection(transItems, new RelationPredicateBucket(TransactionItemFields.TransactionId == _currentDepositTransaction.TransactionId));
	        }

	        foreach (TransferRequestItemEntity item in _transferRequestItems)
	        {
	            if (item.WithdawedQuantity > 0 && item.NewShelfId > 0)
	            {
	                var q = (from t in transItems
	                         where t.RequestItemId == item.Id
	                         select t).FirstOrDefault();

	                TransactionItemEntity transItem;

	                if (q == null)
	                {
	                    transItem = new TransactionItemEntity();

	                    //item.WithdawedQuantity += item.WithdawedQuantity;
	                }
	                else
	                {
	                    transItem = q;

	                    item.WithdawedQuantity += (item.WithdawedQuantity - transItem.Quantity);
	                }

	                item.LastDeliveryDate = AdditionDateDTP.Value.Date;

	                transItem.ShelfId = item.NewShelfId;
	                transItem.StoreId = _currentDepositTransaction.Transaction.StoreId.Value;
	                transItem.ItemId = item.ItemId;
	                transItem.Quantity = item.QuantityToBeAdded;
	                transItem.RequestItemId = item.Id;
	                transItem.UnitPrice = (item.SellingPrice.HasValue) ? item.SellingPrice.Value : 0 ;//.UnitCost * _currentTransferRequest.CurrencyRate;//item.SupplyOrder.CurrencyRate;//Business.GetItemCost(transItem.StoreId, transItem.ShelfId.Value, transItem.ItemId);
	                transItem.SellingPrice = transItem.UnitPrice;

	                _currentDepositTransaction.Transaction.TransactionItems.Add(transItem);
	            }
	            else
	            {
	                var q = (from t in transItems
	                         where t.RequestItemId == item.Id
	                         select t).FirstOrDefault();

	                if (q != null)
	                {
	                    transItemsToDelete.Add(q);
	                }
	            }
	        }

	        DALHelper.DeleteCollection(transItemsToDelete);
            // Addition for Ma7dar elfa7s ////
	        _currentDepositTransaction.ExamRecordNumber = txtExamineDocSerial.Text;
	        _currentDepositTransaction.ExamDate = ExamDateDTP.Value;
            /////////////////////////////////
	        if (DALHelper.SaveEntity(_currentDepositTransaction, true))
	        {
	            _currentTransferRequest.IsProcessed = true;
	            DALHelper.SaveEntity(_currentTransferRequest);
	            DALHelper.SaveCollection(_transferRequestItems);

                using (var context = new ExtendedDataContext())
                {
                    var entity = context.ExamineDocs.Where(x => x.Serial == _currentDepositTransaction.ExamRecordNumber).
                        FirstOrDefault();

                    entity.IsUsedInDepositTransaction = true;

                    context.SubmitChanges();
                }

	            RetrieveTransaction();
	            MessageBox.Show("تم الحفظ بنجاح.");
	        }
	    }

	    private void RetrieveBtn_Click(object sender, EventArgs e)
		{
			RetrieveTransaction();
		}		
		private void RetrieveSupplyOrderBtn_Click(object sender, EventArgs e)
		{
			RetrieveTransferRequest();
		}

		private void StoresDDL_SelectedIndexChanged(object sender, EventArgs e)
		{
			ResetTransactionItems();

			if (StoresDDL.SelectedItem == null)
				return;

			GetShelves();
		}
		private void ProjectsDDL_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (ProjectsDDL.SelectedItem == null)
				return;

			var projectId = (int)((System.Data.DataRowView)(ProjectsDDL.SelectedItem)).Row.ItemArray[0];
            //FormsHelper.LoadComboBox(ToProjectDDL, ProjectFields.Id, ProjectFields.Name, () => Business.GetGeneralProjects(projectId));
			Business.GetItemsPlannedForProject(projectId, _items);
		}
		private void PermitNumberTB_Leave(object sender, EventArgs e)
		{
			ValidatePermitNumber();
		}
		private void _tranItemsForm_RowValidating(int rowIndex, ref bool hasErrors)
		{
			var remainderQuantityCell = _transItemsGrid.Rows[rowIndex].Cells[RemainderQuantity.Index];
            var remainderQuantity = (remainderQuantityCell == null || remainderQuantityCell.Value==null) ? 0 : remainderQuantityCell.Value;

			var quantityCell = _transItemsGrid.Rows[rowIndex].Cells[QuantityToBeAdded.Index];
			var quantity = quantityCell.Value;

			if (quantity == null)
				return;

			if (decimal.Parse(quantity.ToString()) > (decimal.Parse(remainderQuantity.ToString())))
			{
				quantityCell.ErrorText = "الكمية المضافة يجب أن لا تتعدى الكمية المتبقية من الطلب.";
				hasErrors = true;
				return;
			}

			quantityCell.ErrorText = string.Empty;
		}


		private void InitializeDataSources()
		{
			_currentTransaction = new TransactionEntity();
			_currentDepositTransaction = new DepositTransactionEntity();
			_currentDepositTransaction.Transaction = _currentTransaction;			

			BindDataSources();

			EnableDisableControls();
		}
		private void BindDataSources()
		{
			_TransBS.DataSource = _currentTransaction;
			_DepositBS.DataSource = _currentDepositTransaction;
		}
		private void LoadData()
		{
			DALHelper.FetchCollection(_depositTypes, null, null, new SortExpression(DepositTypeFields.Order | SortOperator.Ascending));
			DALHelper.FetchCollection(_inspectionStatus, null, null, new SortExpression(InspectionTypeFields.Order | SortOperator.Ascending));

			FormsHelper.LoadComboBox(SupplierDDL, SupplierFields.Id, SupplierFields.Name, (x, y) => DALHelper.GetDynamicList(x, y, null));
			FormsHelper.LoadComboBox(ProjectsDDL, ProjectFields.Id, ProjectFields.Name, () => Business.GetGeneralProjects());
            //var projectId = (int)((DataRowView)(ProjectsDDL.SelectedItem)).Row.ItemArray[0];
            //FormsHelper.LoadComboBox(ToProjectDDL, ProjectFields.Id, ProjectFields.Name, () => Business.GetGeneralProjects(projectId));
			FormsHelper.LoadComboBox(StoresDDL, StoreFields.Id, StoreFields.Name, ()=>Business.GetStoresForKeeper());

			FormsHelper.CheckStoresAndProjects(StoresDDL.Items, ProjectsDDL.Items, new List<Control>() { _transItemsGrid, SaveBtn }, NoStoresLbl, NoProjectsLbl);

			StatusDDL.SelectedIndex = 0;
			TypeDDL.SelectedIndex = 0;
			SupplierDDL.SelectedIndex = 0;
		}			
		private bool ValidateForm()
		{
			var isValid = true;

			var controls = new List<TextBox>();
			controls.Add(PermitNumberTB);
			//controls.Add(PRNumberTB);
			//controls.Add(PONumberTB);
			controls.Add(SupplyOrderNumberTB);
			//controls.Add(ExamRecordNumberTB);
			//controls.Add(BillOfLadingNmberTB);
			//controls.Add(PlateNumberTB);
			//controls.Add(DriverNameTB);

			if (_errorProviders == null)
			{
				_errorProviders = new List<ErrorProvider>();
			}
			else 
			{
				foreach (var errorProvider in _errorProviders)
				{
					errorProvider.Clear();
					errorProvider.Dispose();
				}
			}
			foreach (var tb in controls)
			{
				if (string.IsNullOrEmpty(tb.Text.Trim()))
				{
					var errorProvider = new ErrorProvider(this);
					_errorProviders.Add(errorProvider);

					errorProvider.SetError(tb, "يجب إدخال قيمة");
					errorProvider.RightToLeft = true;

					isValid = false;
					continue;
				}			
			}

			var combos = new List<ComboBox>();
			combos.Add(StoresDDL);
			//combos.Add(TypeDDL);
			combos.Add(StatusDDL);

			foreach (var cmd in combos)
			{
				if (cmd.SelectedIndex < 0)
				{
					var errorProvider = new ErrorProvider(this);
					_errorProviders.Add(errorProvider);

					errorProvider.SetError(cmd, "يجب إختيار قيمة");
					errorProvider.RightToLeft = true;

					isValid = false;
				}
			}

			if (!ValidatePermitNumber())
				isValid = false;


			_tranItemsForm.ValidateCollection();

			if (_transferRequestItems.Count <= 0)
			{
				isValid = false;
				MessageBox.Show("يجب إضافة أصناف", "خطأ فى الحفظ", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

			return isValid;
		}
		private bool ValidatePermitNumber()
		{
			return FormsHelper.ValidatePermitNumber(this, PermitNumberTB, _errorProviders, "Deposit", _currentTransaction.Id);
		}				
		private void GetShelves()
		{
			var storeId = GetSelectedStoreId();
			_shelves.Clear();
			DALHelper.FetchCollection(_shelves, new RelationPredicateBucket(ShelfFields.StoreId == storeId));
		}		
		private void ResetTransactionItems()
		{
			//if (_tranItemsForm != null)
			//{
			//    _tranItemsForm.Dispose();
			//    _tranItemsForm = null;
			//}

			//var label = new Label();
			//_tranItemsForm = new DataMngrFormBase<TransactionItemEntity>(_supplyOrderItems, _transItemsGrid, _itemsBS, new Button(), label, label, new RelationPredicateBucket(TransactionItemFields.TransactionId == 0));
			//_tranItemsForm.SetNumericFields(new List<int> { 3 });
			//_tranItemsForm.SetMandatoryFields(new List<int>() { 0, 1, 3 });
		}
		private int GetSelectedStoreId()
		{
			var storeId = (int)((System.Data.DataRowView)(StoresDDL.SelectedItem)).Row.ItemArray[0];
			return storeId;
		}		
		private void RetrieveTransaction()
		{
			if (string.IsNullOrEmpty(PermitNumberTB.Text.Trim()))
				return;

			var collection = new EntityCollection<TransactionEntity>();
			var prefetch = new PrefetchPath2(EntityType.TransactionEntity);
			prefetch.Add(TransactionEntity.PrefetchPathDepositTransactions);

			var filter = new RelationPredicateBucket(TransactionFields.Type == "Deposit");
			filter.PredicateExpression.Add(TransactionFields.PermitNumber == PermitNumberTB.Text.Trim());


			var supplyOrderRelations = new RelationCollection();
			supplyOrderRelations.Add(TransferRequestEntity.Relations.ProjectEntityUsingProjectId);

			filter.Relations.Add(TransactionEntity.Relations.DepositTransactionEntityUsingTransactionId);
			filter.PredicateExpression.Add(
				new FieldCompareSetPredicate(DepositTransactionFields.SupplyOrderNumber, null, TransferRequestFields.RequestNumber, null, SetOperator.In, 
					null, supplyOrderRelations));

			DALHelper.FetchCollection(collection, filter, prefetch);

			if (collection.Count <= 0 || collection[0].DepositTransactions.Count <= 0)
			{
				ResetForm();				
			}
			else
			{
				_currentTransaction = collection[0];
				_currentDepositTransaction = _currentTransaction.DepositTransactions[0];

				RetrieveTransferRequest(_currentDepositTransaction.SupplyOrderNumber);

				BindDataSources();

				var transItems = new EntityCollection<TransactionItemEntity>();
				DALHelper.FetchCollection(transItems, new RelationPredicateBucket(TransactionItemFields.TransactionId == _currentDepositTransaction.TransactionId));
				foreach (TransferRequestItemEntity orderItem in _transferRequestItems)
				{
					var q = (from t in transItems
							 where t.ItemId == orderItem.ItemId && t.RequestItemId == orderItem.Id
							 select t).FirstOrDefault();

					if (q == null)
						continue;

					orderItem.NewShelfId = q.ShelfId.Value;
					orderItem.QuantityToBeAdded = q.Quantity;
				}
			}

			ValidatePermitNumber();

			EnableDisableControls();
		}
		private void EnableDisableControls()
		{
            if (_currentDepositTransaction.TransactionStatus == 1)
            {
                _alreadyPricedLbl.Text = "* إذن الإضافه تم حفظه نهائيا ويمكن تسعيره فقط  !";
            }

			var valid = (!_currentDepositTransaction.IsPriced) && (_currentTransferRequest != null) && (!_currentTransferRequest.IsNew);
            var isSubmitted = _currentDepositTransaction.TransactionStatus > 0;

            var isEditable = !((!valid) || isSubmitted);

            _transItemsGrid.Enabled = isEditable;//valid;
            BtnSubmit.Enabled = SaveBtn.Enabled = isEditable;
            bindingNavigator1.Enabled = isEditable;//valid;
			_alreadyPricedLbl.Visible = _currentDepositTransaction.IsPriced;

			//StoresDDL.Enabled = _currentTransaction.IsNew;
            ProjectsDDL.Enabled = isEditable;//_currentTransaction.IsNew;
			//ToProjectDDL.Enabled  =  ProjectsDDL.Enabled = _currentTransaction.IsNew;
			NewBtn.Enabled = !_currentTransaction.IsNew;
			DeleteBtn.Enabled = !(_currentTransaction.IsNew || _currentDepositTransaction.IsPriced);
		}

		private void RetrieveTransferRequest()
		{
			var supplyOrderNumer = SupplyOrderNumberTB.Text;
			ResetForm();
			RetrieveTransferRequest(supplyOrderNumer);
			EnableDisableControls();
		}

		private void RetrieveTransferRequest(string requestNumber)
		{
			if (string.IsNullOrEmpty(requestNumber.Trim()))
				return;

			var collection = new EntityCollection<TransferRequestEntity>();

			var filter = new RelationPredicateBucket(TransferRequestFields.RequestNumber == requestNumber.Trim());
			//filter.PredicateExpression.Add(ProjectFields.IsGeneral == true);
			//filter.Relations.Add(SupplyOrderEntity.Relations.ProjectEntityUsingProjectId);

			DALHelper.FetchCollection(collection, filter);

			if (collection.Count <= 0)
			{
				_currentTransferRequest = new TransferRequestEntity();
				_TransferRequestBS.DataSource = _currentTransferRequest;
			}
			else
			{
				_currentTransferRequest = collection[0];
				_TransferRequestBS.DataSource = _currentTransferRequest;
                SetTransferRequestData(_currentTransferRequest);
			}
			//_requestItems.Clear();
			//DALHelper.FetchCollection(_requestItems, new RelationPredicateBucket(WithdrawRequestItemFields.WithdrawRequestId == _currentRequest.Id));			
			LoadSupplyOrderItems(_currentTransferRequest.Id);
            
			//EnableDisableControls();
		}

        private void SetTransferRequestData(TransferRequestEntity currentRequest)
        {
            var toProj = currentRequest.ToProjectId != null
                             ? GetProjectById(currentRequest.ToProjectId.Value)
                             : null;

            txtToProject.Text = toProj != null
                                            ? toProj.Name
                                            : string.Empty;

            var fromStore = GetStoreById(currentRequest.FromStoreId);
            txtFromStore.Text = fromStore != null
                                            ? fromStore.Name
                                            : string.Empty;
            var toStore = GetStoreById(currentRequest.ToStoreId);
            txtToStore.Text = toStore != null
                                        ? toStore.Name
                                        : string.Empty;
        }

        private StoreEntity GetStoreById(int id)
        {
            var collection = new EntityCollection<StoreEntity>();

            var filter = new RelationPredicateBucket(StoreFields.Id == id);

            DALHelper.FetchCollection(collection, filter);

            if (collection.Count != 0)
                return collection.First();

            return null;
        }


        private ProjectEntity GetProjectById(int id)
        {
            var collection = new EntityCollection<ProjectEntity>();

            var filter = new RelationPredicateBucket(ProjectFields.Id == id);

            DALHelper.FetchCollection(collection, filter);

            if (collection.Count != 0)
                return collection.First();

            return null;
        }

		private void LoadSupplyOrderItems(int supplyOrderId)
		{
			if (_tranItemsForm != null)
			{
				_tranItemsForm.Dispose();
				_tranItemsForm = null;
			}

			var prefetch = new PrefetchPath2(EntityType.TransferRequestItemEntity);
			prefetch.Add(TransferRequestItemEntity.PrefetchPathItem).SubPath.Add(ItemEntity.PrefetchPathUnit_);

			var label = new Label();
			_tranItemsForm = new DataMngrFormBase<TransferRequestItemEntity>(_transferRequestItems, _transItemsGrid, _SupplyOrderItemsBS, new Button(), label, label, new RelationPredicateBucket(TransferRequestItemFields.TransferRequestId == supplyOrderId), prefetch);
			_tranItemsForm.SetNumericFields(new List<int> { QuantityToBeAdded.Index });
			//_tranItemsForm.SetMandatoryFields(new List<int>() {ShelfColumn.Index, QuantityColumn.Index});
			_tranItemsForm.RowValidating += new DataMngrFormBase<TransferRequestItemEntity>.RaiseRowValidating(_tranItemsForm_RowValidating);
		}
		private void ResetForm()
		{
			_currentTransferRequest = new TransferRequestEntity();
			_currentDepositTransaction = new DepositTransactionEntity();
			_currentDepositTransaction.Transaction = new TransactionEntity();
			_transferRequestItems.Clear();

			_DepositBS.DataSource = _currentDepositTransaction;
			_TransBS.DataSource = _currentDepositTransaction.Transaction;
			_TransferRequestBS.DataSource = _currentTransferRequest;
            txtToProject.Text = txtFromStore.Text = txtToStore.Text = string.Empty;
			EnableDisableControls();
		}

		private void _transItemsGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
			if (e.ColumnIndex != QuantityToBeAdded.Index)
				return;

			var itemIdValue = _transItemsGrid.Rows[e.RowIndex].Cells[itemIdDataGridViewTextBoxColumn.Index].Value;
			if (itemIdValue == null)
				return;

			var form = new UnitConverterForm((int)itemIdValue);
			if (form.ShowDialog() == DialogResult.OK)
			{
				_transItemsGrid.SuspendLayout();
				_transItemsGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = form.Value;
				_transItemsGrid.UpdateCellValue(e.ColumnIndex, e.RowIndex);
				_transItemsGrid.ResumeLayout(true);
			}
		}

		private void SearchBtn_Click(object sender, EventArgs e)
		{
			//var transferRequestRelations = new RelationCollection();
			//transferRequestRelations.Add(TransferRequestEntity.Relations.ProjectEntityUsingProjectId);

			var filter = new RelationPredicateBucket(TransactionFields.Type == "Deposit");
			filter.Relations.Add(TransactionEntity.Relations.ProjectEntityUsingProjectId);
			filter.Relations.Add(TransactionEntity.Relations.DepositTransactionEntityUsingTransactionId);
			filter.PredicateExpression.Add(
				new FieldCompareSetPredicate(DepositTransactionFields.SupplyOrderNumber, null, TransferRequestFields.RequestNumber, null, SetOperator.In,
					new PredicateExpression(TransferRequestFields.IsProcessed == true)/*, transferRequestRelations*/));


			var searchForm = new SearchForm(TransactionFields.PermitNumber, TransactionFields.ProjectId, TransactionFields.Date, filter, () => Business.GetGeneralProjects());
			if (searchForm.ShowDialog() == DialogResult.OK)
			{
				PermitNumberTB.Text = searchForm.SelectedNumber;
				RetrieveTransaction();
			}
		}

		private void SearchSupplyOrderBtn_Click(object sender, EventArgs e)
		{
			var filter = new RelationPredicateBucket();
			filter.Relations.Add(TransferRequestEntity.Relations.ProjectEntityUsingProjectId);
			filter.PredicateExpression.Add(TransferRequestFields.IsProcessed == true);

			//var searchForm = new SearchSupplyOrderForm(TransferRequestFields.RequestNumber, TransferRequestFields.ProjectId, TransferRequestFields.Date, filter, () => Business.GetGeneralProjects());
			//if (searchForm.ShowDialog() == DialogResult.OK)
			//{
			//    SupplyOrderNumberTB.Text = searchForm.SelectedNumber;
			//    RetrieveSupplyOrder();
			//}
			var searchForm = new SearchForm(TransferRequestFields.RequestNumber, TransferRequestFields.ProjectId, TransferRequestFields.Date, filter, () => Business.GetRunningProjects());
			if (searchForm.ShowDialog() == DialogResult.OK)
			{
				SupplyOrderNumberTB.Text = searchForm.SelectedNumber;
				RetrieveTransferRequest();
			}
		}

		private void DeleteBtn_Click(object sender, EventArgs e)
		{
			var form = new DeleteConfirmationForm();

			if (form.ShowDialog() == DialogResult.Yes)
			{
				if (DALHelper.DeleteEntity(_currentTransaction))
				{
					ResetForm();
				}
			}
		}

        private void BtnSubmitClick(object sender, EventArgs e)
        {
            var form = new SaveConfirmationForm();

            if (form.ShowDialog() == DialogResult.Yes)
            {
                _currentDepositTransaction.TransactionStatus = 1;
                Save();
                Business.StoreItems(GetSelectedStoreId(), _currentDepositTransaction, _currentTransaction);
            }
        }

        private void btnSearchExamineDoc_Click(object sender, EventArgs e)
        {
            SearchExamineDoc searchForm = _currentTransferRequest == null
                                    ? new SearchExamineDoc(true)
                                    : new SearchExamineDoc(_currentTransferRequest.Id, true);
                                       
            if (searchForm.ShowDialog() == DialogResult.OK)
            {
                PopulteExamineTransfer(searchForm.SelectedNumber);
            }
        }

        private void btnRetriveExaminOrder_Click(object sender, EventArgs e)
        {
            PopulteExamineTransfer(txtExamineDocSerial.Text);
        }

        private void PopulteExamineTransfer(string ExaminOrderSerial)
        {
            var examine = Business.GetExamineBySerial(ExaminOrderSerial);

            if (examine == null)
            {
                var errorProvider = new ErrorProvider(this);
                errorProvider.SetError(txtExamineDocSerial, "محضر الفحص غير موجود");
                return;
            }

            ExamDateDTP.Value = examine.CreationDate;
            ExamDateDTP.Enabled = false;

            // Get transfer if Examination was chosen
            TransferRequestEntity transferRequestEntity = Business.GetTransferRequestByIdOrNumber(examine.TransferRequestId.Value);

            if (transferRequestEntity != null)
            {
                SupplyOrderNumberTB.Text = transferRequestEntity.RequestNumber;
                RetrieveTransferRequest();
                // Use this method to replace transfer order Qty with Examine Qty
                SyncTransferItemsWithExamineItems();
            }
            else
            {
                SupplyOrderNumberTB.Text = string.Empty;
            }
        }

        private void SyncTransferItemsWithExamineItems()
        
        {
            ExamineDoc examine = Business.GetExamineBySerial(txtExamineDocSerial.Text);

            if(examine == null)
             return;

            int count = 0;


            List<TransferRequestItemEntity> deletedTransferRequestItems = new List<TransferRequestItemEntity>();
            foreach (TransferRequestItemEntity transferRequestItem in _transferRequestItems)
            {
                var examineDocItem =
                    examine.ExamineDocItems.Where(x => x.ItemId == transferRequestItem.ItemId).FirstOrDefault();

                _transItemsGrid.Rows[count].Cells[quantityDataGridViewTextBoxColumn.Index].Value = examineDocItem != null ?
                                                                                    examineDocItem.Quantity :
                                                                                    transferRequestItem.Quantity;

                if (examineDocItem == null)
                {
                    deletedTransferRequestItems.Add(transferRequestItem);
                }
                else if (examineDocItem.Quantity == 0)
                {
                    deletedTransferRequestItems.Add(transferRequestItem);
                }
                               
                //Just work around to remove delivered quantity that not bind to the current examin doc
                //if ((transferRequestItem.WithdawedQuantity != 0) && (examineDocItem.Quantity == 0))
                //{
                //    _transItemsGrid.Rows[count].Cells[DeliveredQuantity.Index].Value = (decimal)0.00000;
                //}
                //else
                //{
                //    _transItemsGrid.Rows[count].Cells[DeliveredQuantity.Index].Value = transferRequestItem.WithdawedQuantity;
                //}

                count++;
            }

            //Remove supplyOrderItems
            foreach (TransferRequestItemEntity transferRequestItem in deletedTransferRequestItems)
            {
                _transferRequestItems.Remove(transferRequestItem);
            }

           

            if (examine.IsAccepted.Value)
            {
                StatusDDL.SelectedIndex = 0;
            }
            else
            {
                StatusDDL.SelectedIndex = 3;
            }
            //for (int i = 0; i < _transItemsGrid.Rows.Count - 1; i++)
            //{
            //    _transItemsGrid.Rows[i].Cells[RemainderQuantity.Index].Value = examine.ExamineDocItems[i].Quantity;
            //}

           _transItemsGrid.Refresh();
        }
        //private void ToProjectDDL_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    if (ToProjectDDL.SelectedItem == null)
        //        return;

        //    var projectId = (int)((System.Data.DataRowView)(ToProjectDDL.SelectedItem)).Row.ItemArray[0];
        //    Business.GetItemsPlannedForProject(projectId, _items);
        //}
	}
}
